package org.tzeng.html.extra;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.tzeng.html.bean.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 涛 on 2015/12/11.
 */
public class CtripExtra {

    private static final Logger logger = Logger.getLogger(CtripExtra.class);

    public CtripExtra() {

    }

    public static PageInfo extraGInfo(String file, TravelInfo travel){
        PageInfo pi = null;

        Document doc = Jsoup.parse(file, "UTF-8");
        String docStr = doc.toString();
        String detail = docStr.substring(docStr.indexOf("/*详情页配置*/") + 30, docStr.indexOf("/*加载详情页*/") - 7).trim();

        JSONObject jsono = JSON.parseObject(JSON.parseObject(detail).getString("data"));
        BaseInfo baseInfo = JSON.parseObject(JSON.parseObject(JSON.parseArray(jsono.getString("TraceLogBuriedPoint")).get(0).toString()).getString("Value"), BaseInfo.class);

        String pname = doc.getElementsByTag(travel.getProduct_name()).first() != null ? StringUtil.normaliseWhitespace(doc.getElementsByTag("title").first().text()).trim() : "";

        String titleStr = doc.title();
        Pattern pattern = Pattern.compile("[0-9]+日");
        Matcher matcher = pattern.matcher(titleStr);
        int days = 0;
        if (matcher.find())
            days = Integer.parseInt(matcher.group().replaceAll("日", ""));

        Elements nums = doc.select(travel.getProduct_num());
        String num = "";
        if (nums != null && nums.size() > 0)
            num = nums.get(0).html();

        Elements product_citys = doc.select(travel.getProduct_city());
        String product_city = "";
        if (product_citys != null && product_citys.size() > 0)
            product_city = product_citys.get(0).html();

        Element providers = doc.select(travel.getProvider_href()).first();
        String provider_href = "", provider_name = "";
        if (null != providers) {
            provider_href = providers.attr("href");
            provider_name = providers.html() + "TT" + providers.attr("title");
        }

        Elements specials = doc.select(travel.getSpecial_info());
        String special_info = "";
        if (specials != null)
            special_info = specials.html();

        Elements simple_routes = doc.select(travel.getSimple_route());
        String simple_route = "";
        if(simple_routes != null)
            simple_route = simple_routes.html().replaceAll("\n", "");

        Elements pm_recommends = doc.select(travel.getPm_recommend());
        String pm_recommend = "";
        if(pm_recommends != null)
            pm_recommend = pm_recommends.html().replaceAll("★ ", "");

        Element score = doc.select(travel.getComment_wrap()).first();
        double scoreD = -1.0d;
        if(score != null){
            scoreD = Double.parseDouble(score.text().split(" ")[0]);
        }

        // 日历价格
        //List<DPrice> prices = getdGPrices(doc, travel);

        Element today_p = doc.select(travel.getToday_price()).first();
        int today_price = 0;
        if(today_p != null){
            //  && "实时计价".equals(today_p.html())
        	/*
        	 * trimNum(today_p.html().replaceAll("<[^>]+>", "").replaceAll("¥", ""))
        	 * */
            if(trimNum(today_p.html().replaceAll("<[^>]+>", "").replaceAll("¥", "")).length() > 0){
                today_price = Integer.parseInt(trimNum(today_p.html().replaceAll("<[^>]+>", "").replaceAll("¥", "")));
            }
        }

        pi = new PageInfo();
        pi.setProduct_name(pname);
        pi.setProduct_num(baseInfo.getProductid());
        pi.setProduct_to_city(baseInfo.getTo_poi().getPoiname());
        pi.setProduct_city(baseInfo.getFrom().getCityname());
        pi.setProvider_href(provider_href);
        pi.setProvider_name(provider_name);
        pi.setSpecial_info(special_info);
        pi.setSimple_route(simple_route);
        pi.setPm_recommend(pm_recommend);
        pi.setComment_wrap(scoreD / 5.0d);
        pi.setToday_price(today_price);
        pi.setProduct_days(days);
//        pi.setPrices(prices);
        return pi;
    }

    private static List<DPrice> getdGPrices(Document doc, TravelInfo travel) {
        List<DPrice> prices = new ArrayList<DPrice>();
        Element date = doc.select(travel.getJs_calendar()).first();
        String d = "";
        if(date == null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            long start = System.currentTimeMillis();
            d = sdf.format(start);
        }else{
            d = trimNum(date.html());
            if(d.length() < 6){
                String month = d.substring(4);
                d = d.substring(0, 4) + "0" + month;
            }
        }

        Elements dps = doc.select(travel.getDetail_calendar());
        String dp = "";
        for (Element ele : dps){
            dp += ele.html().replaceAll("<[^>]+>", "").replaceAll("¥", "") + " ";
        }

        String[] strs = dp.split("\\s+");
        int ilen = strs.length;
        for (int i = 0; i + 1 < ilen; i++) {
            String tt = d + trimNum(strs[i]);
            int next = Integer.parseInt(trimNum(strs[i + 1]));
            DPrice price = new DPrice();
            if (next > 31){
                price.setPrice(next);
                price.setDtime(tt);
                i ++;
            } else {
                price.setPrice(-1);
                price.setDtime(tt);
            }
            prices.add(price);
        }

        // TODO 日期价格对应，目前的处理方法不合适，会出现01月变成13月或00月，以后要完善
        int iplen = prices.size();
        int f = -1, s = -1;
        for (int i = 0; i < iplen; i ++){
            if (f == -1 && (prices.get(i).getDtime()).substring(6).equals("01")) {
                f = i;
            }
            if (f >= 0 && (prices.get(i).getDtime()).substring(6).equals("01")){
                s = i;
            }
            if (f < 0 && s < 0){
                DPrice dd = prices.get(i);
                //dd.setDtime(LocalDate.parse(dd.getDtime(), DateTimeFormatter.BASIC_ISO_DATE).minusMonths(1).format(DateTimeFormatter.BASIC_ISO_DATE));
                dd.setDtime(Integer.parseInt(dd.getDtime()) - 100 + "");
            }else if (f == s){

            }else if (s > f){
                DPrice dd = prices.get(i);
                //dd.setDtime(LocalDate.parse(dd.getDtime(), DateTimeFormatter.BASIC_ISO_DATE).plusMonths(1).format(DateTimeFormatter.BASIC_ISO_DATE));
                dd.setDtime(Integer.parseInt(dd.getDtime()) + 100 + "");
            }

        }
        return prices;
    }

    public static String trimNum(String num){
        String result = "";
        for (int i = 0; i < num.length(); i ++){
            if(num.charAt(i)>=48 && num.charAt(i)<=57){
                result+=num.charAt(i);
            }
        }

        return result;
    }

    public static PageInfo extraFInfo(String file, TravelInfo travel){
        PageInfo pi = null;

        Document doc = Jsoup.parse(file, "UTF-8");
        doc.title();
        String pname = doc.getElementsByTag(travel.getProduct_name()).first() != null ? StringUtil.normaliseWhitespace(doc.getElementsByTag("title").first().text()).trim() : "";

        Element providers = doc.select(travel.getProvider_href()).first();
        String provider_href = "", provider_name = "";
        if (null != providers) {
            provider_href = providers.attr("href");
            provider_name = providers.html() + "TT" + providers.attr("title");
        }

        Elements specials = doc.select(travel.getSpecial_info());
        String special_info = "";
        if (specials != null)
            special_info = specials.html();

        Elements simple_routes = doc.select(travel.getSimple_route());
        String simple_route = "";
        if (simple_routes != null)
            simple_route = simple_routes.html().replaceAll("\n", "");

        Elements pm_recommends = doc.select(travel.getPm_recommend());
        String pm_recommend = "";
        if(pm_recommends != null)
            pm_recommend = pm_recommends.text().replaceAll("★ ", "");

        Element score = doc.select(travel.getComment_wrap()).first();
        double scoreD = -1.0d;
        if (score != null)
            scoreD = Double.parseDouble(score.text().split(" ")[0]);

        Element today_p = doc.select(travel.getToday_price()).first();
        int today_pI = -1;
        if (today_p != null)
            today_pI = Integer.parseInt(trimNum(today_p.html().replaceAll("<[^>]+>", "").replaceAll("¥", "")));
        else if (doc.select("strong#J_total_price") != null){
            today_pI = Integer.parseInt(trimNum(doc.select("strong#J_total_price").html().replaceAll("<[^>]+>", "").replaceAll("¥", "")));
        }

        // 日历价格
//        List<DPrice> prices = getdFPrices(doc, travel);

        String docStr = doc.toString();
        String detail = docStr.substring(docStr.indexOf("FRTPage.extend(") + 15, docStr.indexOf("FHXConfig") - 11).trim();
        JSONObject jsono = JSON.parseObject(JSON.parseObject(detail.replaceAll("<[^>]+>", "")).getString("DATA"));

        String titleStr = doc.title();
        Pattern pattern = Pattern.compile("[0-9]+日");
        Matcher matcher = pattern.matcher(titleStr);
        int days = 0;
        if (matcher.find())
            days = Integer.parseInt(matcher.group().replaceAll("日", ""));

        pi = new PageInfo();
        pi.setProduct_name(StringEscapeUtils.unescapeHtml(jsono.getString("ProductName")));
        pi.setProduct_to_city(jsono.getString("DestinationCityName"));
        pi.setProduct_num(jsono.getString("ProductId"));
        pi.setProduct_city(jsono.getString("StartCityName"));
        pi.setProvider_href(provider_href);
        pi.setProvider_name(provider_name);
        pi.setSpecial_info(special_info);
        pi.setSimple_route(simple_route);
        pi.setPm_recommend(pm_recommend);
        pi.setToday_price(today_pI);
        pi.setComment_wrap(scoreD / 5.0d);
        pi.setProduct_days(days);
//        pi.setPrices(prices);
        return pi;
    }

    private static List<DPrice> getdFPrices(Document doc, TravelInfo travel) {
        List<DPrice> prices = new ArrayList<DPrice>();
        Elements dps = doc.select(travel.getDetail_calendar());
        String dp = "", priceStr = "";
        for (Element ele : dps){
            dp += ele.attr("date") + " ";
            if("".equals(ele.getElementsByClass("calendar_price01").html().replaceAll("<[^>]+>", "").replaceAll("¥", ""))){
                priceStr += "-1 ";
            }else{
                priceStr += ele.getElementsByClass("calendar_price01").html().replaceAll("<[^>]+>", "").replaceAll("¥", "") + " ";
            }
        }

        String[] dpStrs = dp.split("\\s+"), priceStrs = priceStr.split("\\s+");
        int ilen = dpStrs.length;
        for (int i = 0; i < ilen; i++) {
            DPrice price = new DPrice();
            price.setPrice(Integer.parseInt(priceStrs[i]));
            price.setDtime(dpStrs[i].replaceAll("-", ""));
            prices.add(price);
        }

        return prices;
    }

    public static void main(String[] args) {

    }

}